


export type CellValue = number | string;
export default class ChessboardState {
    public static _Instance: ChessboardState | null = null;
    static get instance(): ChessboardState {
        if (!ChessboardState._Instance) {
            ChessboardState._Instance = new ChessboardState();
        }
        return ChessboardState._Instance;
    }
    private _rows = 0;
    private _cols = 0;
    private _board: CellValue[][] = [];

    static init(rows: number, cols: number, initValue: CellValue = 0): void {
        const inst = ChessboardState.instance;
        inst._rows = rows;
        inst._cols = cols;

        inst._board = Array.from({ length: rows }, () =>
            Array.from({ length: cols }, () => initValue)
        )
        console.log(inst._board, 'inst._board ')
    }

    /**
     * 
        外部坐标转成内部坐标
     */
    static toInternal(row: number, col: number): { r: number, c: number } {
        const inst = ChessboardState.instance;
        const r = col;
        const c = inst._cols - 1 - row;
        return { r, c }
    }

    static toExternal(row: number, col: number): { r: number, c: number } {
        const inst = ChessboardState.instance;
        const r = inst._cols - 1 - col;
        const c = row;
        return { r, c }
    }


    static setBoard(row: number, col: number, cellValue: CellValue): void {
        const inst = ChessboardState.instance
        const { r, c } = ChessboardState.toInternal(row, col);
        inst._board[r][c] = cellValue;
        // console.log(inst._board, '设置棋盘状态的数据')
    }
    static getBoard(): CellValue[][] {
        const inst = ChessboardState.instance
        return inst._board;
        // console.log(inst._board, '设置棋盘状态的数据')
    }
    static findPosByvalue(value: CellValue): Array<{ row: number, col: number }> {
        const inst = ChessboardState.instance;
        const result: Array<{ row: number, col: number }> = [];

        for (let i = 0; i < inst._rows; i++) {
            for (let j = 0; j < inst._cols; j++) {
                if (inst._board[i][j] == value) {
                    let rc = ChessboardState.toExternal(i, j)
                    result.push({ row: rc.r, col: rc.c })
                }
            }
        }


        return result;
    }

    static findValue(x, z) {
        const inst = ChessboardState.instance;
        let newXY = ChessboardState.toInternal(x, z)
        return !!inst._board[newXY.r][newXY.c]
    }

    static clearValue(target: CellValue, defaultValue = 0): void {
        const inst = ChessboardState.instance;
        for (let i = 0; i < inst._rows; i++) {
            for (let j = 0; j < inst._cols; j++) {
                if (inst._board[i][j] === target) {
                    inst._board[i][j] = defaultValue;
                }
            }
        }
    }
}